;(function ($) {
	$.widget("bpm.costsCentres", {
		options: {
			maxItensOnList: 6
		},
		_create: function() {
			var self = this;
			
			self._createToggle();
		},
		_createToggle: function() {
			var self = this,
				button = null;

			self._disabled = self.element.data("disabled") == true;
				
			button = 
				$("<button>")
					.addClass("btn btn-success btn-sm popup-marker")
					.attr({ "type": "button", "data-container": "body", "data-toggle": "popover", "data-placement": "bottom", "data-title": "Utilização de Centros de Custos" })
					.text(" Centros de Custos");
			
			button.prepend($("<span>").addClass("glyphicon glyphicon-list"));
			
			button.popover({ content: self._setupCostsCentres(), html: true, delay: { show: 100, hide: 0 } })
	        	.on("shown.bs.popover", function() {
	        		var availableList = $("#availableList"),
	        			selectionList = $("#selectionList");
	        		$("#availableList, #selectionList").sortable({
	        			items: "li",
						axis: "y",
						cursor: "move",
						opacity: 0.7,
						placeholder: "ui-state-highlight",
						connectWith: ".dd-list",
						disabled: self._disabled
					}).disableSelection();
	        		availableList.on("sortupdate", function( event, ui ) {
	        			$(this).children("li").each(function() {
		    				self._renameItem($(this));
		    			});
	        			self._toggleDisplay(availableList);
	        		});
	        		selectionList.on("sortupdate", function( event, ui ) {
	        			var i = 1;
	        			selectionList.children("li").each(function() {
		    				self._renameItem($(this), i++);
		    			});
	        			
	        			self._toggleDisplay(selectionList);
	        			
	        			self.element.val(selectionList.sortable("toArray", {attribute: "data-id"}));
	        		});
	        		if (self.element.val() != "") {
	        			var selectedItens = self.element.val().split(",");
	        			for (var i = 0; i < selectedItens.length; i++) {
	        				availableList.find("[data-id='" + selectedItens[i] + "']").remove().appendTo(selectionList);
	        			}
	        			$(".dd-empty", selectionList).hide();
	        		}
	        		availableList.trigger("sortupdate");
	        		selectionList.trigger("sortupdate");
	        		
	        		$("#addAllCostsCentres, #removeAllCostsCentres").tooltip();
	        		$("#addAllCostsCentres").click(function(e) {
	        			self._transferAll(availableList, selectionList);
	        		});
	        		$("#removeAllCostsCentres").click(function(e) {
	        			self._transferAll(selectionList, availableList);
	        		});
				});
			
			self.element.after(button);
		},
		_renameItem: function(item, order) {
			var textHolder = item.children(":first");
			if (order == undefined) {
				if (!isNaN(textHolder.text().charAt(0))) {
					textHolder.text(textHolder.text().substring(3));
				}
			} else {
				if (isNaN(textHolder.text().charAt(0))) {
					textHolder.text(order + ". " + textHolder.text());
				} else {
					textHolder.text(order + ". " + textHolder.text().substring(3));
				}
			}
		},
		_setupCostsCentres: function() {
			var self = this,
				htmlContent = '',
				costsCentres = self.options.costsCentres;			
			
			htmlContent += '<label>Disponíveis:</label>';
			htmlContent += '<div class="dd"><ol id="availableList" class="dd-list">';
			htmlContent += '<div class="dd-empty" style="display: none">Todos itens estão selecionados</div>';
			for (var i = 0; i < costsCentres.length; i++) {
				htmlContent += '<li class="dd-item" data-id="' + costsCentres[i].id + '">';
				htmlContent += '	<div class="dd-handle' + (self._disabled ? ' ui-state-disabled' : '') + '">' + costsCentres[i].name + '</div>'; 
				htmlContent += '</li>';
			}
			htmlContent += '</ol></div>';
			
			htmlContent += '<label>Selecionados:</label> ';
			htmlContent += '<button id="removeAllCostsCentres" class="btn btn-default btn-xs' + (self._disabled ? ' disabled' : '') + '" type="button" data-toggle="tooltip" title="Remover todos" style="float: right;"><span class="glyphicon glyphicon-hand-up"></span></button>';
			htmlContent += '<button id="addAllCostsCentres" class="btn btn-default btn-xs' + (self._disabled ? ' disabled' : '') + '" type="button" data-toggle="tooltip" title="Adicionar todos" style="float: right; margin-right: 10px;"><span class="glyphicon glyphicon-hand-down"></span></button>';
			htmlContent += '<div class="dd"><ol id="selectionList" class="dd-list">';
			htmlContent += '<div class="dd-empty">Arraste aqui os itens desejados</div>';
			htmlContent += '</ol></div>';
			
			return htmlContent;
		},
		_toggleDisplay: function(list) {
			if (list.children("li").length === 0) {
				$(".dd-empty", list).show();
			} else {
				$(".dd-empty", list).hide();
			}
		},
		_transferAll: function(from, to) {
			$("li", from).each(function(index) {
				$(this).remove().appendTo(to);
			});
			from.trigger('sortupdate');
			to.trigger('sortupdate');
		}
	});
	
	$('body').on('click', function (e) {
		$('[data-toggle="popover"]').each(function () {
			if (!$(this).is(e.target) && $(this).has(e.target).length === 0 && $('.popover').has(e.target).length === 0) {
	  			$(this).popover('hide');
			}
		});
	});
})(jQuery);